﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace Joyeon.Utils
{
    public static class XmlUtil
    {
        /// <summary>
        /// 将一个对象序列化为xml字符串
        /// </summary>
        /// <param name="objectToSerialize"></param>
        /// <returns></returns>
        public static string Serialize(object objectToSerialize)
        {
            MemoryStream mem = new MemoryStream();
            XmlSerializer ser = new XmlSerializer(objectToSerialize.GetType());
            ser.Serialize(mem, objectToSerialize);
            ASCIIEncoding ascii = new ASCIIEncoding();
            return ascii.GetString(mem.ToArray());
        }
        /// <summary>
        /// 将一个xml字符串反序列化为一个对象
        /// </summary>
        /// <param name="typeToDeserialize"></param>
        /// <param name="xmlString"></param>
        /// <returns></returns>
        public static object Deserialize(Type typeToDeserialize, string xmlString)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(xmlString);
            MemoryStream mem = new MemoryStream(bytes);
            return Deserialize(typeToDeserialize, mem);
        }
        /// <summary>
        /// 将一个xml的流对象反序列化为一个指定对象。
        /// </summary>
        /// <param name="typeToDeserialize"></param>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static object Deserialize(Type typeToDeserialize, MemoryStream stream)
        {
            XmlSerializer ser = new XmlSerializer(typeToDeserialize);
            return ser.Deserialize(stream);
        }
    }
}
